import 'dart:convert';

import 'package:dulu/config/global.dart';
import 'package:dulu/iconfont.dart';
import 'package:dulu/manager/main_manager.dart';
import 'package:dulu/pages/editor.dart';
import 'package:dulu/pages/momt.dart';
import 'package:dulu/route-trans.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MoodTablePage extends StatefulWidget {
  MoodTablePage({Key key, this.year, this.month, this.day}) : super(key: key);
  final int year;
  final int month;
  final int day;
  @override
  _MoodTablePageState createState() => _MoodTablePageState();
}

class _MoodTablePageState extends State<MoodTablePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      color: const Color(0xFFFFFFFF),
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.only(left: 37, right: 39),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Global.fontSecondColor.withOpacity(.15),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    width: 25,
                    height: 15,
                  ),
                  SizedBox(width: 5),
                  Text(
                    '未记录',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(width: 15),
                  Container(
                    decoration: BoxDecoration(
                      color: Global.happyColor,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    width: 25,
                    height: 15,
                  ),
                  SizedBox(width: 5),
                  Text(
                    '开心',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(width: 15),
                  Container(
                    decoration: BoxDecoration(
                      color: Global.generalColor,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    width: 25,
                    height: 15,
                  ),
                  SizedBox(width: 5),
                  Text(
                    '一般',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(width: 15),
                  Container(
                    decoration: BoxDecoration(
                      color: Global.sadColor,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    width: 25,
                    height: 15,
                  ),
                  SizedBox(width: 5),
                  Text(
                    '难过',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 25),
            Container(
              padding: const EdgeInsets.only(left: 37, right: 39),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  BottomTitle(title: 'Sun'),
                  BottomTitle(title: 'Mon'),
                  BottomTitle(title: 'Tue'),
                  BottomTitle(title: 'Wed'),
                  BottomTitle(title: 'Thu'),
                  BottomTitle(title: 'Fri'),
                  BottomTitle(title: 'Sat'),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              padding: const EdgeInsets.only(left: 35, right: 35),
              child: MoodTable(
                  year: widget.year, month: widget.month, day: widget.day),
            ),
          ],
        ),
      ),
    );
  }
}

class BottomTitle extends StatefulWidget {
  BottomTitle({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _BottomTitleState createState() => _BottomTitleState();
}

class _BottomTitleState extends State<BottomTitle> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width / 9.2,
      child: Center(
        child: Text(
          widget.title,
          style: TextStyle(
            color: Global.fontSecondColor,
            fontFamily: 'Arciform',
            fontSize: 15,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }
}

class MoodTable extends StatefulWidget {
  MoodTable({Key key, this.year, this.month, this.day}) : super(key: key);
  final int year;
  final int month;
  final int day;
  @override
  _MoodTableState createState() => _MoodTableState();
}

class _MoodTableState extends State<MoodTable> {
  int checkedDay = DateTime.now().day; //默认选中当天
  Color checkedMoodColor = Global.generalColor;
  List checkedMoodMomt = [];
  var checkedMoodData;

  @override
  void initState() {
    checkedDay = widget.day; //默认选中当天
    super.initState();
  }

  // 判断当前年份是否是闰年
  bool leap(year) {
    return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0;
  }

  List<Widget> getEveryDay(y, m, queryMoodFromDate) {
    List ms = [31, leap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    List<Widget> daysWidget = [];
    int placeholderLength =
        DateTime.parse('$y-${m > 9 ? m : "0" + m.toString()}-01').weekday % 7;
    for (var i = 0; i < placeholderLength; i++) {
      daysWidget.add(Container(
        width: MediaQuery.of(context).size.width / 9.5,
        height: MediaQuery.of(context).size.width / 9.5,
        margin: EdgeInsets.all(2),
      ));
    }
    for (var i = 1; i < ms[m - 1] + 1; i++) {
      var dateData = queryMoodFromDate(y, m, i);
      var color;
      if (dateData == null) {
        color = Color(0xFFDFDFDF);
      } else {
        switch (dateData['mood']) {
          case 1:
            color = Global.happyColor;
            break;
          case 0:
            color = Global.generalColor;
            break;
          case -1:
            color = Global.sadColor;
            break;
        }
      }
      if (checkedDay == i) {
        setState(() {
          checkedMoodColor = color;
          checkedMoodMomt =
              dateData != null ? json.decode(dateData['momt']) : [];
          checkedMoodData = dateData;
        });
      }
      daysWidget.add(
        InkWell(
          onTap: () {
            setState(() {
              checkedDay = i;
              checkedMoodMomt =
                  dateData != null ? json.decode(dateData['momt']) : [];
              checkedMoodData = dateData;
            });
          },
          child: Container(
            width: MediaQuery.of(context).size.width / 9.5,
            height: MediaQuery.of(context).size.width / 9.5,
            margin: EdgeInsets.all(2),
            decoration: BoxDecoration(
                color: color.withOpacity(.7),
                borderRadius: BorderRadius.circular(7),
                border: Border.all(
                  width: 3,
                  color: checkedDay == i ? color : Colors.transparent,
                )),
            child: Center(
              child: Text(
                i.toString(),
                style: TextStyle(
                  color: checkedDay == i
                      ? Global.fontColor.withOpacity(.3)
                      : Global.fontColor.withOpacity(.15),
                  fontWeight: FontWeight.w600,
                  fontFamily: 'Arciform',
                  fontSize: checkedDay == i ? 20 : 17,
                ),
              ),
            ),
          ),
        ),
      );
    }
    return daysWidget;
  }

  List<Widget> renderCheckedMoodMomt(_mainManager, momt) {
    List<Widget> list = [];
    for (var i = 0; i < momt.length; i++) {
      var item = momt[i];
      list.add(
        InkWell(
          onTap: () {
            Navigator.of(context).push(CustomRoute(MomtPage(
              year: widget.year,
              month: widget.month,
              day: checkedDay,
              content: item['content'],
              timestamp: item['timestamp'],
            )));
          },
          child: Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 1,
                  color: Global.fontSecondColor.withOpacity(.1),
                ),
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      DateTime(item['timestamp']).hour.toString() +
                          ':' +
                          DateTime(item['timestamp']).minute.toString(),
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Global.fontSecondColor,
                        fontFamily: 'Kuaile',
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        openMenuBottomSheet(_mainManager, momt, item);
                      },
                      child: Container(
                        width: 40,
                        child: Icon(
                          IconFont.menu1,
                          size: 15,
                          color: Global.fontSecondColor,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 5),
                Text(
                  item['content'],
                  style: TextStyle(
                    fontSize: 17,
                    fontWeight: FontWeight.w600,
                    color: Global.fontColor,
                    fontFamily: 'Kuaile',
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                )
              ],
            ),
          ),
        ),
      );
    }
    return list;
  }

  Future openMenuBottomSheet(mainManager, momt, item) async {
    await showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          margin: EdgeInsets.all(15),
          padding: EdgeInsets.all(10),
          height: 100,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: Global.backgroundColor,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                offset: Offset(0, 5),
                blurRadius: 10,
                spreadRadius: 6,
              )
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              InkWell(
                onTap: () async {
                  Navigator.of(context).pop();
                  momt.removeWhere(
                      (_item) => _item['timestamp'] == item['timestamp']);
                  var queryRes = await mainManager.queryDayMood(
                      widget.year, widget.month, checkedDay);
                  if (queryRes.length > 0) {
                    mainManager.updateMoodMomt(queryRes[0]['id'], momt);
                  }
                },
                child: Container(
                  width: 300,
                  padding: EdgeInsets.fromLTRB(10, 7, 10, 7),
                  decoration: BoxDecoration(
                    color: Color(0xFFFC244B),
                    borderRadius: BorderRadius.circular(20),
                    boxShadow: [
                      BoxShadow(
                        color: Color(0xFFFC244B).withOpacity(.5),
                        offset: Offset(2, 3),
                        blurRadius: 3,
                        spreadRadius: 1,
                      )
                    ],
                  ),
                  child: Center(
                    child: Text(
                      '删除该心情瞬间',
                      style: TextStyle(
                        fontWeight: FontWeight.w900,
                        fontSize: 16,
                        color: Global.backgroundColor,
                        fontFamily: 'Kuaile',
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          Wrap(
            children: getEveryDay(
                widget.year, widget.month, _mainManager.queryMoodFromDate),
          ),
          SizedBox(height: 20),
          checkedMoodData == null
              ? Container()
              : InkWell(
                  onTap: () {
                    Navigator.of(context).push(CustomRoute(MoodEditorPage(
                      year: widget.year,
                      month: widget.month,
                      day: checkedDay,
                    )));
                  },
                  child: Container(
                    width: 200,
                    padding: EdgeInsets.fromLTRB(10, 7, 10, 7),
                    decoration: BoxDecoration(
                      color: checkedMoodColor,
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: checkedMoodColor.withOpacity(.5),
                          offset: Offset(2, 3),
                          blurRadius: 3,
                          spreadRadius: 1,
                        )
                      ],
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          IconFont.manual,
                          color: Global.backgroundColor,
                          size: 20,
                        ),
                        SizedBox(width: 7),
                        Text(
                          '记录心情瞬间',
                          style: TextStyle(
                            fontWeight: FontWeight.w900,
                            fontSize: 16,
                            color: Global.backgroundColor,
                            fontFamily: 'Kuaile',
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
          Column(
            children: renderCheckedMoodMomt(_mainManager, checkedMoodMomt),
          )
        ],
      ),
    );
  }
}
